using System;
using System.Collections.Generic;
using System.Linq;
using Newtonsoft.Json;

namespace RFS.Domain.PaiShi.WorkFlow
{
    public class WorkFlowNode : IWorkFlowNode
    {
        public WorkFlowNode(IEnumerable<IOrderItem> ors =default,  DateTime startDate =default , DateTime endDate=default,string nodeName="" )
        {
            OrderItems = ors ?? new List<IOrderItem>();
            
            KeyName = nodeName??"无名";
            StartAt = startDate==default ?  DateTime.Today : startDate;
            EndAt =  EndAt==default ?  startDate : endDate;
            if ((EndAt - StartAt).TotalHours < 24)
            {
                StartAt = StartAt.Date;
                EndAt = StartAt.Date.AddDays(1);
            }
        }

 
        // public WorkFlowNode(  )
        // {
        //     OrderItems = ors ?? new List<IOrderItem>();
        //     
        //     KeyName = nodeName??"无名";
        //     StartAt = startDate==default ?  DateTime.Now | startDate;
        //     EndAt = endDate ?? DateTime.Now;
        // }


        public override string ToString()
        {
            return  $"[日期：{StartAt:d} ->{(EndAt-StartAt).TotalDays:0.#}天,总量：{Quantiy},单数:{Count}]";
        }


        private IList<IOrderItem> _dataItems=new List<IOrderItem>();

        public string KeyName { get; set; }
        public string BatchNo { get; set; }
        public decimal Quantiy { get; set; }
        public decimal Amount { get; set; }
        public int Count { get ; set; }
        public bool IsTheLastNode { get; set; }
        public bool IsCheckOutPoint { get; set; }
        public IWorkFlowNode ParentNode { get; set; }
        public IEnumerator<IWorkFlowNode> ChildrenNodes { get; set; }
        public IEnumerator<IWorkFlowNode> GetAllChildren { get; set; }
        public bool IsEmpty { get; set; } = false;

        [JsonIgnore]
        public IEnumerable<IOrderItem> OrderItems
        {
            get => _dataItems;
            set
            {
                _dataItems = value.ToList(); 
                Recalculate();
            }
        }

        public DateTime StartAt { get; set; }
        public DateTime EndAt { get; set; }

        public IOrderItem  FirstDateItem
        {
            set;
            get;
        }

        public IEnumerable<IOrderItem> GetUnRecordedItems { get=> _dataItems.Where(x=>!x.RecordedInAcc) ; }

        public void Recalculate()
        {
            Quantiy = OrderItems.Sum(x => x.Quantity);
            Amount = OrderItems.Sum(x => x.Amount);
            Count = OrderItems.Count();
            FirstDateItem = OrderItems.FirstOrDefault();
        }

        public void Clear()
        {

            _dataItems = new List<IOrderItem>();
        }

        public static WorkFlowNode OfEmpty( )
        {
            var n = new WorkFlowNode();
            n.ParentNode=null ;
            n.KeyName = "空";
            n.IsEmpty=true;
        
            return n;
        }
        
    }
}